package com.mllweb.api.core.office;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Prject: data
 * @Package: com.gcbaoli.data.core
 * @author: feejson
 * @date: 2017/9/7 10:32
 * @version: V1.0
 */
public class ExcelReader implements OfficeReader {
    private File file;
    private FileInputStream inputStream;
    private Workbook workbook;
    private Sheet sheet;

    /**
     * @param file
     * @throws IOException
     */
    public void appoint(String file) throws IOException {
        this.file = new File(file);
        this.inputStream = new FileInputStream(this.file);
        createWorkbook(file);
        currentSheet(0);
    }

    /**
     * 生成当前工作副本
     *
     * @param file
     * @throws IOException
     */
    private void createWorkbook(String file) throws IOException {
        String suffix = file.substring(file.lastIndexOf(".") + 1);
        if ("xls".equals(suffix)) {
            this.workbook = new HSSFWorkbook(this.inputStream);
        } else if ("xlsx".equals(suffix)) {
            this.workbook = new XSSFWorkbook(this.inputStream);
        } else {
            this.workbook = new XSSFWorkbook(this.inputStream);
        }
    }

    /**
     * 切换当前页
     *
     * @param sheetIndex
     */
    public void currentSheet(int sheetIndex) {
        this.sheet = this.workbook.getSheetAt(sheetIndex);
    }

    /**
     * 读取当前行
     *
     * @param rowIndex
     * @return
     */
    public Row readRow(int rowIndex) {
        return this.sheet.getRow(rowIndex);
    }

    /**
     * 获取总行数
     *
     * @return
     */
    public int rowNum() {
        return this.sheet.getLastRowNum() + 1;
    }

    /**
     * 获取当前行数据
     *
     * @param rowIndex
     * @return
     */
    public List<Object> readRowCell(int rowIndex) {
        List<Object> list = new ArrayList<Object>();
        Row row = this.sheet.getRow(rowIndex);
        Iterator<Cell> cellIterator = row.cellIterator();
        while (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();
            if (cell.getCellTypeEnum() == CellType.STRING) {
                list.add(cell.getStringCellValue());
            } else if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                list.add(cell.getNumericCellValue());
            } else if (cell.getCellTypeEnum() == CellType.BOOLEAN) {
                list.add(cell.getBooleanCellValue());
            } else if (cell.getCellTypeEnum() == CellType.FORMULA) {
                list.add(cell.getCellFormula());
            } else if (cell.getCellTypeEnum() == CellType.ERROR) {
                list.add(cell.getErrorCellValue());
            } else {
                list.add("");
            }
        }
        return list;
    }


}
